<template>
	<view class="container">
		<view class="state-area dflex navbar-area bg-main">
			
			<view class="nav-item dflex-c pos-r fs h-full" :class="{ active: tabCurrentIndex === index }"
				v-for="(item, index) in navList" :key="index" @click="tabClick(item,index)">
				{{ item.state }}
			</view>
	
		</view>
		
		<view class="padding-lr margin-bottom-sm" v-for="(item, index) in orderList" :key="index">
			
			
			
			<!-- 订单项 -->
			<view class="order-item padding bg-main border-radius">
				<view @click="todetail(item.id)">
				<!-- <view> -->
					<!-- 订单商品明细 -->
					<view class="goods-area" :class="{ 'margin-top': goodsIndex > 0 }"
						v-for="(goodsItem, goodsIndex) in item.products" :key="goodsIndex">
						<image :src="goodsItem.defaultImg" mode="aspectFill"></image>
						<view class="right flex1">
							<text class="clamp-2">{{ goodsItem.title }}</text>
							<text class="clamp-2">{{ goodsItem.price || 0 }}</text>
							<view class="ft-dark fs-xs padding-top-xs">
								<text class="margin-right">× {{goodsItem.orders_products.pcount || 0}}</text>
							</view>
							<view class="margin-top-sm">
								<text class="price ft-main fs-sm">{{ goodsItem.orders_products.sprice || 0  }}</text>
							</view>
						</view>
					</view>

					<!-- 实付款 -->
					<view class="dflex-e">
						<text class="fs-xs margin-right-xs">实付款</text>
						<text class="price ft-main">{{ item.totals || 0 }}</text>
					</view>
				</view>

				<!-- 订单操作区 -->
				<view class="dflex-b margin-top-sm">
					<view>	
						<!-- 当前状态 -->
						<text class="ft-dark" v-if="item.status == 0">待付款</text>
						<text class="ft-dark" v-else-if="item.status == 1">已付款</text>
						<text class="ft-dark" v-else-if="item.status == 2">待发货</text>
						<text class="ft-dark" v-else-if="item.status == 3">已发货</text>
						<text class="ft-dark" v-else-if="item.status == 4">退款处理中</text>
						<text class="ft-dark" v-else-if="item.status == 5">已退款</text>
						<text class="ft-dark" v-else-if="item.status == 6">已完成</text>
						<text class="ft-dark" v-else>已取消</text>
					</view>

					<view class="dflex-e">
						<view class="dflex" v-if="item.status == 0">
							<button class="action-btn border-radius-big bg-main" @click="cancelOrder(item)">取消订单</button>

							<button v-if="item.status == 0" class="action-btn border-radius-big bg-main main-btn" 
								@click="payment(item)">立即支付</button>
							
						</view>
						<view class="dflex" v-if="[1, 2, 3].includes(item.status)">
							<button class="action-btn border-radius-big bg-main" @click="torefund(item)">申请退款</button>
						</view>
						<!-- <button v-if="!item.order.order_refund_state && 
								['待收货', '待评价', '已完成'].includes(item.order.state)" class="action-btn border-radius-big bg-main"
							@click="toexpress(item)">查看物流</button> -->
						<view class="dflex" v-if="item.status == 3">
							<button class="action-btn border-radius-big bg-main main-btn" @click="toreceipt(item)">确认收货</button>
						</view>
						<!-- 				<view class="dflex" v-if="item.order.state == '待评价'">
							<button class="action-btn border-radius-big bg-main main-btn"
								@click="toevaluate(item)">我要评价</button>
						</view> -->
						<view class="dflex" v-if="[7, 5, 6].includes(item.status)">
							<button class="action-btn border-radius-big bg-main main-btn" @click="delOrder(item)">删除订单</button>
						</view>
						
					</view>
				</view>
			</view>
		</view>
	</view>
</template>


<script>
	const _order = 'usemall-order'
	import {
		mapState
	} from 'vuex';

	import {
		queryOrdersApi,
		queryOneOrdersApi,
		operateOrdersApi,
		payOrdersApi,
		deleteOrdersApi,
	} from  "@/api/order.js"
	
	
	export default {
		computed: {
			...mapState(['islogin', 'member'])
		},

		data() {
			return {
				tabCurrentIndex: 0,

				navData: {},

				navList: [{
						id: 0,
						state: '全部',
						status: '',
					},
					{
						id: 1,
						state: '已付款',
						status: '1',
					},
					// {
					// 	id: 2,
					// 	state: '待发货',
					// 	status: '2',
					// },
					{
						id: 3,
						state: '待收货',
						status: '3',
					},
					{
						id: 5,
						state: '已完成',
						status: '6',
					},
					{
						id: 4,
						state: '退款中',
						status: '4',
					},
					
					{
						id: 6,
						state: '已退款',
						status: '5',
					},
					// {
					// 	id: 7,
					// 	state: '已取消',
					// 	status: '7',
					// },
				],
				orderList: [], // 订单数据
				pages: {
					currentPage: 1, // 当前页数
					pageSize: 10, // 一页多少条
					total: 0, // 总数居条数
				},
				scrollLeft: 0,
				title: '全部',
				status: '',
				orderStatus: '',
				
				// 订单id
				order_id: '',
				
				//订单修改后状态
				order_status: '',
				
				//订单总额
				order_totals: '',
			};
		},
		watch: {
			tabCurrentIndex(nv, ov) {
				this.loadData('tab_change', 1);
			}
		},
		onShow(options) {
			// let _this = this;
			// if (!this.islogin) {
			// 	uni.showModal({
			// 		title: '授权登录',
			// 		success: function(res) {
			// 			if (res.confirm) {
			// 				_this.$api.tologin();
			// 			} else if (res.cancel) {
			// 				_this.$api.tohome();
			// 			}
			// 		}
			// 	});
			// 	return;
			// }

			// let state = '';

			// uni.getStorage({
			// 	key: '__order_state',
			// 	success(res) {
			// 		state = res.data;
			// 		console.debug(state, "<=+==+++++++getStorage.state");
			// 		let cur_nav = _this.navList.find(x => x.state == state);
			// 		if (cur_nav) {
			// 			_this.tabCurrentIndex = cur_nav.id;
			// 		}

			// 		uni.removeStorage({
			// 			key: '__order_state'
			// 		});
			// 	},
			// 	complete() {
			// 		_this.loadData('refresh');
			// 	}
			// });
		},

		onLoad(options) {
			uni.$on('__event_order', res => {
				if (res == 'refresh') {
					this.loadData('refresh');
				}
			});

			this.loadData();

		},
		// 下拉刷新
		onPullDownRefresh() {
			this.loadData('refresh');
		},
		// 上拉加载更多
		onReachBottom() {
			if (this.pages.currentPage * this.pages.pageSize < this.pages.total) {
				this.pages.currentPage++;
				this.loadData();
			}
		},
		methods: {
			// 获取订单列表
			async loadData() {
				uni.showLoading({
					title: "加载中..."
				})
				if(!this.orderStatus){	
					this.getOrdersFunc();
				}
				//查询全部订单
				// const response = await queryOrdersApi({
				// 	uid: this?.member?.id ?? "",
				// 	currentPage: this?.pages?.currentPage ?? 1,
				// 	pageSize: this?.pages?.pageSize ?? 10,
				// 	status: this.orderStatus,
				// }).catch(() => {});
				// console.log('🚀🚀🚀🚀🚀 response - queryOrdersApi: ', response);
				// if (response?.code === 200) {
				// 	const _data = [...this.orderList, ...(response?.data?.records ?? [])];

				// 	this.$set(this, 'orderList', _data);
				// 	console.debug(this.orderList, "<====");
				// 	this.pages.total = response?.data?.total;
				// } else {
				// 	this.$api.msg(response?.msg ?? '服务器繁忙，请稍后再试');
				// }
				uni.hideLoading();
			},



			// 查询用户全部订单
			async getOrdersFunc() {
				const response = await queryOrdersApi({
					uid: this?.member?.id ?? "",
					currentPage: this?.pages?.currentPage ?? 1,
					pageSize: this?.pages?.pageSize ?? 10,
					status: this.orderStatus,
				}).catch(() => {});
				console.log('🚀🚀🚀🚀🚀 response - queryOrdersApi: ', response);
				if (response?.code === 200) {
					const _data = [...this.orderList, ...(response?.data?.records ?? [])];

					this.$set(this, 'orderList', _data);
					console.debug(this.orderList, "<====");
					this.pages.total = response?.data?.total;
				} else {
					this.$api.msg(response?.msg ?? '服务器繁忙，请稍后再试');
				}
			},

			// swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				// this.getOrdersFunc();
			},
			//顶部tab点击
			tabClick(item, index) {

				this.tabCurrentIndex = index;
				 
				this.orderStatus = item?.status ?? '';
				this.pages.currentPage = 1,
					this.pages.total = 0;
				this.orderList = [];
				// this.loadData();
				this.getOrdersFunc();

			},

			// 点击跳转详情页面
			todetail(order_id) {
				uni.navigateTo({
					url: `/pages/user/order/order-detail?order_id=${order_id}`
				});
			},



			// 删除订单
			delOrder(item) {
				let _this = this;

				uni.showModal({
					title: '提示',
					content: '删除订单',
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
								title: '请稍后'
							});
							
							_this.deleteOrderFunc(item);
						} else if (res.cancel) {
							console.log('点击取消');
						}
					},
					complete() {
						uni.hideLoading();
					}
				});
			},

			// 取消订单
			cancelOrder(item) {
				let _this = this;

				uni.showModal({
					title: '提示',
					content: '取消订单',
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
								title: '请稍后'
							});
							console.debug(item,"<=================取消订单item")
							_this.order_status = 7;
							_this.operateOrdersFunc(item);
							
							
							// _this.$func.usemall.call('order/cancel', {
							// 	order_id: item.order.order_id,
							// 	state: '已取消'
							// }).then(res => {
							// 	if (res.code === 200) {
							// 		_this.loadData('tab_change', 1);
							// 	}
							// })
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					},
					complete() {
						uni.hideLoading();
					}
				});
			},
			
			
			
			// 查看物流
			toexpress(item) {
				this.$api.msg('查看物流开发中');
				// uni.navigateTo({
				// 	url: `/pages/user/order/order-express?order_id=${item.order.order_id}`
				// });
			},
			// 确认收货
			toreceipt(item) {
				let _this = this;

				uni.showModal({
					title: '提示',
					content: '确认收货',
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
								title: '请稍后'
							});
							
							console.debug(item,"<=================确认收货item")
							
							_this.order_status = 6;
							_this.operateOrdersFunc(item);
							// _this.$func.usemall.call('order/received', {
							// 	order_id: item.order.order_id,
							// 	state: '待评价'
							// }).then(res => {
							// 	_this.loadData('tab_change', 1);
							// });
				
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					},
					complete() {
						uni.hideLoading();
					}
				});
			},
		
				
				// //申请退款
				async torefund(item) {
					let _this = this;
				
					uni.showModal({
						title: '提示',
						content: '申请退款',
						success: await
						function(res) {
							if (res.confirm) {
								uni.showLoading({
									title: '请稍后'
								});
				
								_this.order_status = 4;
								_this.operateOrdersFunc(item);
				
								// _this.$func.usemall.call('order/cancel', {
								// 	order_id: _this.order_id,
								// 	state: '已取消'
								// }).then(res => {
								// 	if (res.code === 200) {
								// 		_this.loadData('refresh');
								// 	}
								// })
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						},
						complete() {
							uni.hideLoading();
						}
					});
				},
				
		
			// 评价
			toevaluate(item) {
				// uni.navigateTo({
				// 	// url: `/pages/user/order/order-evaluate?id=${item.order.order_id}`
				// });
			},
			
		
			
			//用户删除订单
			async deleteOrderFunc(item){
				this.order_id = item.id
				const response = await deleteOrdersApi({
					order_id: this?.order_id ?? '',
					
				}).catch(() => {});
				if (response?.code === 200) {
					
					this.$api.msg("订单删除成功");
					setTimeout(() => {
					        this.tabClick();
					    }, 2000); // 这里的 3000 表示等待 3 秒
				}else{
					this.$api.msg("服务器繁忙，稍后再试");
				}
				return;
			},
			
			
			
		// 立即支付
		// payment(order) {
		// 	if (order.order_pay_state == '待核实') {
		// 		this.$api.msg('订单已支付待核实状态');
		// 		return;
		// 	}
		
		// 	this.$api.topay({
		// 		order_id: order.order_id,
		// 		money: order.order_actural_paid
		// 	});
		// },
			
			
			
			
			

		
		// 立即支付
		async payment(item) {
			let _this = this;
		
			uni.showModal({
				title: '提示',
				content: '确认支付',
				success: await function(res) {
					if (res.confirm) {
						uni.showLoading({
							title: '请稍后'
						});
						console.debug(item.totals,"<=====================item.totals")
						console.debug(_this.member.totals,"<=====================_this.member.totals")
						if ((_this.member.totals - item.totals) >= 0 ) {							
							_this.payOrdersFunc(item);

						} else {
							_this.$api.msg("余额不足，请充值");
							
						}
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				},
				complete() {
					uni.hideLoading();
				}
			});
		},
		
		//用户支付扣除余额
		async payOrdersFunc(item) {
		
			console.debug(item,"<=========================payOrdersFunc----item")
			console.debug(this?.member?.id, "<=================payOrdersFunc +++ this?.member?.id")
			console.debug(item?.totals,"<=================payOrdersFunc +++ item?.totals")
			const response = await payOrdersApi({
				uid: this?.member?.id ?? '',
				order_totals: item?.totals ?? '',
			}).catch(() => {});
			if (response?.code === 200) {
				// this.getOneOrdersFunc();
				this.order_status = 1;
				this.operateOrdersFunc(item);
				this.$api.msg("支付成功");
				setTimeout(() => {
				        this.tabClick();
				    }, 2000); // 这里的 2000 表示等待 2 秒
			} 
			else {
				this.$api.msg(response?.msg ?? "服务器繁忙支付失败");
			}
			return;
		},
		
		
		//修改用户订单数据
		async operateOrdersFunc(item) {
			console.debug(item,"<====================operateOrdersFunc")
			this.order_id = item.id
			console.log(this.order_status, "<================= caozuo_his?.order_status")
			console.log(this.order_id, "<================= caozuo_his?order_id")
		
			const response = await operateOrdersApi({
				id: this?.order_id ?? '',
				status: this?.order_status ?? '',
			}).catch(() => {});
			if (response?.code === 200) {
				this.$api.msg("操作成功");
				// this.tabClick();
				setTimeout(() => {
				        this.tabClick();
				    }, 2000); // 这里的 3000 表示等待 3 秒
			}
			
			return;
		},
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		}
	};
</script>

<style lang="scss">
	page,

	.container {
		min-height: 100%;
		background: $page-color-base;
	}

	/* 订单状态区 */
	.navbar-area {
		white-space: nowrap;
	}

	.state-area {
		height: 7vh;
		box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
		z-index: 10;
		top: 0;
	}

	.nav-item {
		flex: 1;

		&.active {
			&:after {
				content: '';
				position: absolute;
				left: 50%;
				transform: translate(-50%);
				bottom: 0;
				width: 44px;
				height: 0;
				border-bottom: 2px solid $base-color;
			}
		}
	}

	/* 订单轮播区 */
	.swiper-area {
		height: 93vh;
	}

	/* 订单区 */
	.order-area {}


	/* 订单项 */
	.order-item {

		/* 订单商品明细区 */
		.goods-area {
			display: flex;

			image {
				width: 180rpx;
				height: 180rpx;
			}

			.right {
				padding: 0 30upx 0 24upx;
				overflow: hidden;

				.attr-box {
					font-size: $font-sm + 2upx;
					color: $font-color-light;
					padding: 10upx 12upx;
				}
			}
		}

		/* 操作按钮 */
		.action-btn {
			width: 156rpx;
			height: inherit;
			line-height: inherit;
			margin: 0;
			margin-left: 20rpx;
			padding: 12rpx 0;
			font-size: $font-sm + 2upx;
			color: $font-color-dark;
			/* #ifdef MP-QQ || MP-ALIPAY */
			border: 1px solid;
			/* #endif */

			&:after {
				border-radius: 100px;
			}

			&.main-btn {
				background: #fff9f9;
				color: $base-color;

				&:after {
					border-color: #f7bcc8;
				}
			}
		}
	}
</style>